package com.house365.core.sop.weixin;

import android.content.Context;

import com.house365.core.sop.Constants;
import com.house365.core.sop.Util;
import com.house365.core.sop.bean.Share;
import com.house365.core.sop.bean.ShareType;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendMessageToWX;
import com.tencent.mm.sdk.openapi.WXMediaMessage;
import com.tencent.mm.sdk.openapi.WXTextObject;

/**
 * 微信初始化
 * 
 * @author Administrator
 * 
 */
public class WXEntryApp {
	// IWXAPI 是第三方app和微信通信的openapi接口
	private IWXAPI api;
	private Share share;

	public WXEntryApp(Context context, Share share,IWXAPI api) {
		// TODO Auto-generated constructor stub
		this.api=api;
		this.share = share;
		boolean register = api.registerApp(Constants.WEIXIN_APP_ID);
		if (register) {
			sendMultiData();
		}
	}

	/**
	 * 发送多种类型的微信数据
	 */
	private void sendMultiData() {
		WXMediaMessage msg = new WXMediaMessage();
		if (share.getShareType()== ShareType.TXT) {
			WXTextObject textObject = new WXTextObject();
			textObject.text = share.getDescription();
			msg.mediaObject = textObject;
		}else {
			if (null != share.getMediaObject()) {
				msg.mediaObject = share.getMediaObject();
			}
		}

		// 发送文本类型的消息时，title字段不起作用
		msg.title = share.getTitle();
		if(share.isFriendCircle()){
			msg.title = share.getTitle() +" "+share.getDescription() ;
		}
		msg.description = share.getDescription();
		if (null != share.getThumbData()) {
			msg.thumbData = share.getThumbData();
		}else if (share.getThumb() != null) {
			byte[] bytes = Util.compressImage(share.getThumb(), 32);
			msg.thumbData = bytes;
		}
		SendMessageToWX.Req req = new SendMessageToWX.Req();
		req.transaction = buildTransaction(share.getShareType().toString());
		req.message = msg;
		req.scene = share.isFriendCircle() ? SendMessageToWX.Req.WXSceneTimeline
				: SendMessageToWX.Req.WXSceneSession;
		api.sendReq(req);
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}
}
